<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Iris
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Iris_Model_ConfigHandler extends Iris_Abstract_ModelHandler
{
	protected $object  = 'Iris_Model_Config';
	protected $table   = 'config';
	protected $primary = 'id';

	protected $preferences = array();

	public function __construct()
	{
		parent::__construct();

		$this->preferences = $this->_getPreferences();
	}

	public function getConfigs()
	{
		$configs = array();

		$configModels = $this->loadConfigs();

		foreach ( $configModels as $configModel )
		{
			$name = $configModel->getVar('name');
			$configs[$name] = $configModel->getVar('value');
		}

		return $configs;
	}

	public function load($id = null)
	{
		$model = parent::load($id);
		$this->_setData($model);

		return $model;
	}

	public function find($criteria = null, $orderby = null, $sort = 'ASC', $limit = 0, $start = 0)
	{
		$models = parent::find($criteria, $orderby, $sort, $limit, $start);

		if ( is_array($models) )
		{
			foreach ( $models as &$model )
			{
				$this->_setData($model);
			}
		}
		else
		{
			$this->_setData($model);
		}

		return $models;
	}

	public function loadByName($name = null)
	{
		$name = mysql_real_escape_string($name);

		$obj = $this->create();

		if ( strlen($name) )
		{
			$sql = "SELECT * FROM `%s` WHERE `%s`='%s'";
			$sql = sprintf($sql, $this->table, 'name', $name);
			$rsrc = $this->_query($sql, 1);
			$vars = $this->db->fetchArray($rsrc);

			if ( is_array($vars) )
			{
				$obj->unsetNew();
				$obj->setVars($vars);
			}
		}

		return $obj;
	}

	public function deleteConfigsNotIn($configNames)
	{
		$criteria = new Iris_Class_Criteria();
		$criteria->add('name', 'NOT IN', $configNames);

		return $this->delete($criteria);
	}

	public function loadConfigs()
	{
		$configNames = array_keys($this->preferences);

		$criteria = new Iris_Class_Criteria;
		$criteria->add('name', 'IN', $configNames);

		return $this->find($criteria);
	}

	protected function _getPreferences()
	{
		require IRIS_PATH.DS.'config'.DS.'preference.php';

		if ( !isset($configs) or !is_array($configs) ) return array();

		$preferences = array();

		foreach ( $configs as $config )
		{
			if ( !isset($config['name']) or !strlen($config['name']) )
			{
				continue;
			}

			$preferences[$config['name']] = $config;
		}

		return $preferences;
	}

	protected function _setData(&$model)
	{
		$name = $model->getVar('name');

		if ( isset($this->preferences[$name]) )
		{
			$model->setData($this->preferences[$name]);
		}
	}
}

?>
